#!/usr/bin/env python
# coding: utf-8

import boto3
from loguru import logger

logger.add("change_address.log")

client = boto3.client('ec2',region_name='us-west-1')


def get_instance_id():
    response = client.describe_instances()
    instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']
    return instance_id


class ElasticIPController:
    def __init__(self, instanceid):
        self.eip = ''
        self.instanceid = instanceid
        self.instanceip = self.describe_instance_address()

    def __repr__(self):
        return f"origin ip: {self.instanceip}"

    def describe_instance_address(self):
        response = client.describe_instances(
            InstanceIds=[
                self.instanceid,
            ],
        )

        return response['Reservations'][0]['Instances'][0]['PublicIpAddress']

    def allocate_address(self):
        response = client.allocate_address()
        self.eip = response['PublicIp']

    def associate_address(self):
        response = client.associate_address(
            InstanceId=self.instanceid,
            PublicIp=self.eip, )

    def disassociate_address(self):
        response = client.disassociate_address(PublicIp=self.eip, )

    def release_address(self, allocation_id):
        response = client.release_address(
            AllocationId=allocation_id,
        )

    def describe_elastic_address(self):
        response = client.describe_addresses(
        )

        return response['Addresses'][0]['AllocationId']

    def change_address(self):
        self.allocate_address()
        self.associate_address()
        self.instanceip = self.describe_instance_address()
        return self.instanceip

    def rollback(self):
        self.disassociate_address()
        allocation_id = self.describe_elastic_address()
        self.release_address(allocation_id)
        self.instanceip = self.describe_instance_address()
        return self.instanceip


# def test():
#     ip_controller = ElasticIPController(instance_id)
#     current_ip = ip_controller.instanceip
#     # signup program
#     ip1 = ip_controller.change_address()
#     # signup program
#     ip2 = ip_controller.rollback()
#     # signup program


if __name__ == '__main__':
    # test()
    get_instance_id()